package com.liangxy.news.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Utility class for date formatting
 */
public class DateUtils {
    
    private static final SimpleDateFormat INPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    private static final SimpleDateFormat OUTPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
    private static final SimpleDateFormat DATE_ONLY_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
    
    /**
     * Format date string to a readable format
     * @param dateString Date string in format "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd"
     * @return Formatted date string
     */
    public static String formatDate(String dateString) {
        if (dateString == null || dateString.isEmpty()) {
            return "";
        }
        
        try {
            Date date;
            // 判断日期格式是否包含时间
            if (dateString.contains(":")) {
                date = INPUT_FORMAT.parse(dateString);
            } else {
                date = DATE_ONLY_FORMAT.parse(dateString);
            }
            
            if (date == null) {
                return dateString;
            }
            
            return OUTPUT_FORMAT.format(date);
        } catch (ParseException e) {
            // Try with date only format
            try {
                Date date = DATE_ONLY_FORMAT.parse(dateString);
                if (date == null) {
                    return dateString;
                }
                
                return DATE_ONLY_FORMAT.format(date);
            } catch (ParseException ex) {
                return dateString;
            }
        }
    }
    
    /**
     * Get current date time in format "yyyy-MM-dd HH:mm:ss"
     * @return Current date time string
     */
    public static String getCurrentDateTime() {
        return INPUT_FORMAT.format(new Date());
    }
    
    /**
     * Get current date in format "yyyy-MM-dd"
     * @return Current date string
     */
    public static String getCurrentDate() {
        return DATE_ONLY_FORMAT.format(new Date());
    }
} 